<script setup lang="ts">
import {Warning} from "@element-plus/icons-vue";
import {reqUserInfo, reqCertationType, reqUserCertation} from "@/api/user/user.ts";
import {onMounted, reactive, ref} from "vue";
import type {OneUserInfoResData,OneUserInfo,CertationArr,CertationTypeResponseData,UserParams} from "@/api/user/type.ts";
import {ElMessage, FormInstance, UploadInstance} from "element-plus";
let householdRegistrationType = ref<CertationArr>([])
onMounted(() => {
  getUserInfo()
  //获取证件类型
  getType()
})
async function getType(){
  let res:CertationTypeResponseData = await  reqCertationType()
  householdRegistrationType.value=res.data
}
//用户信息的映射
let userInfo = ref<OneUserInfo>({
  authStatus: 0,
  certificatesNo: "",
  certificatesType: "",
  certificatesUrl: null,
  createTime: "",
  id: 0,
  isDeleted: 0,
  name: "",
  nickName: null,
  openid: null,
  param: {},
  phone: "",
  status: 0,
  updateTime: ""
})
/**
 * 获取用户信息
 */
async function getUserInfo() {
  let res: OneUserInfoResData = await reqUserInfo()
  userInfo.value=res.data
  // console.log(res)
}
//收集用户表单的数据
let userFormInfo = reactive<UserParams>({
  "certificatesNo": '',
  "certificatesType": '',
  "certificatesUrl": '',
  "name": ''
})
/**
 * 超出上传文件的约束数量提示
 */
function exceedHandler(){
  ElMessage({type:'warning',message:'文件超出数量'})
}
/**
 * 上传文件
 * @param response 上传成功响应数据
 * @param uploadFile 上传文件的信息
 * @param uploadFiles 上传文件数组的信息
 */
function successHandler(response:any,uploadFile:any,uploadFiles:any){
  userFormInfo.certificatesUrl=response.data
  formRef.value?.clearValidate('certificatesUrl')
  // console.log(userFormInfo.certificatesUrl)
}
let showImageDialogVisible =ref<boolean>(false)
/**
 *放大上传图片的钩子
 * @param uploadFile
 */
function showImage(){
  showImageDialogVisible.value=true
  // console.log(uploadFile)
}
/**
 * 删除文件清空路径
 */
function removeUpload(){
  userFormInfo.certificatesUrl=''
}
//对文件上传组件的引用
let fileUpload =ref<UploadInstance>()
/**
 * 清空表单的信息
 */
function resetFormData(){
  for (const key in userFormInfo) {
    userFormInfo[key]=''
  }
  fileUpload.value?.clearFiles()
}
/**
 * 提交信息
 */
async function submit(){
  formRef.value?.validate(res=>{
    if(res){
      // try {
      //   await reqUserCertation(userFormInfo)
      //   ElMessage({type:'success',message:'认证成功'})
      //   await getUserInfo()
      //   // console.log(res)
      // }catch (e){
      //   ElMessage({type:'error',message:'认证失败'})
      // }
    }else {
      return false
    }
  })
}
/**
 * 自定义校验用户名
 * @param rule 规则
 * @param value 输入框的值
 * @param callback  放行
 */
function validateName(rule: any, value: any, callback: any){
  const reg = /^[\u00B7\u3007\u3400-\u9FFF\uE000-\uF8FF\uF900-\uFAFF\u{20000}-\u{2FFFF}\u{30000}-\u{3FFFF}]+$/u;
  if(reg.test(value)){
    callback()
  }else {
    callback(new Error('名字格式错误'))
  }
}
/**
 * 验证身份证号码的格式
 * @param rule
 * @param value
 * @param callback
 */
function validateNo(rule: any, value: any, callback: any){
  const IDCard_RGEX = /(^\d{15})|(^\d{17}(x|X|\d))/;
  if(IDCard_RGEX.test(value)){
    callback()
  }else {
    callback(new Error('身份证格式错误'))
  }
}
/**
 * 验证身份户籍类型
 * @param rule
 * @param value
 * @param callback
 */
function validateType(rule: any, value: any, callback: any){
  if(value=='10'||value=='20'){
    callback()
  }else {
    callback(new Error('身份类型错误'))
  }
}
/**
 * 校验图片是否为空
 * @param rule
 * @param value
 * @param callback
 */
function validateUrl(rule: any, value: any, callback: any){
  if(value.length){
    callback()
  }else {
    callback(new Error('图片路径不能为空'))
  }
}
//用户信息的校验规则
const rules=reactive({
  certificatesNo:[{required:true,validator:validateNo,trigger:'change'}],
  name: [{required:true,validator:validateName,trigger:'change'}],
  certificatesType:[{required:true,validator:validateType,trigger:'change'}],
  certificatesUrl:[{required:true,validator:validateUrl}]
})
let formRef =ref<FormInstance>()


</script>

<template>
  <div class="certification">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>实名信息</span>
        </div>
      </template>
      <div>
        <div class="tips" v-if="userInfo.authStatus==0">
          <el-icon style="line-height: 32px;">
            <Warning/>
          </el-icon>
          <p>你必须先完成实名认证才能，进行接下来的操作，请在输入框内填写相关的信息。</p>
        </div>
        <el-descriptions
            class="margin-top"
            :column="1"
            border
            v-if="userInfo.authStatus==1"
        >
          <el-descriptions-item :width="50" label-align="center">
            <template #label>
              <div class="cell-item">
                用户姓名
              </div>
            </template>
            {{ userInfo.name }}
          </el-descriptions-item>
          <el-descriptions-item :width="50" label-align="center">
            <template #label>
              <div class="cell-item">
                证件类型
              </div>
            </template>
            {{ userInfo.certificatesType=='10'?'身份证':'户口本' }}
          </el-descriptions-item>
          <el-descriptions-item :width="50" label-align="center">
            <template #label>
              <div class="cell-item">
                证件号码
              </div>
            </template>
            {{ userInfo.certificatesNo }}
          </el-descriptions-item>
        </el-descriptions>
        <el-form
            ref="formRef"
            label-width="100px"
            class="ruleForm"
            v-else
            :model="userFormInfo"
            :rules="rules"
        >
          <el-form-item label="用户姓名" prop="name">
            <el-input v-model="userFormInfo.name" placeholder="请输入用户姓名"/>
          </el-form-item>
          <el-form-item label="证件类型" prop="certificatesType">
            <el-select placeholder="请输入证件类型" style="width: 100%;" v-model="userFormInfo.certificatesType">
              <el-option :label="item.name" :value="item.value" v-for="item in householdRegistrationType" v-bind:key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="证件号码" prop="certificatesNo">
            <el-input placeholder="请填写证件号码" v-model="userFormInfo.certificatesNo"/>
          </el-form-item>
          <el-form-item label="上传证件" prop="certificatesUrl">
<!--            action="/api/oss/file/fileUpload?fileHost=userAuah"-->
            <el-upload
                list-type="picture-card"
                :limit="1"
                :on-success="successHandler"
                :on-exceed="exceedHandler"
                action="/api/oss/file/fileUpload?fileHost=userAuah"
                :on-preview="showImage"
                :on-remove="removeUpload"
                ref="fileUpload"
            >
              <img src="@/assets/images/auth_example.png" alt="" style="width: 100%;height: 100%;">
            </el-upload>
            <el-dialog v-model="showImageDialogVisible" width="40%">
              <img v-if="userFormInfo.certificatesUrl" :src="userFormInfo.certificatesUrl" alt="上传的图片" style="width: 100%;height: 100%;"/>
            </el-dialog>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submit">提交</el-button>
            <el-button @click="resetFormData">重写</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.certification {
  padding: 30px 30px;
  .tips {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    margin-bottom: 15px;
  }
  .ruleForm {
    width: 80%;
  }
}
</style>